package com.gurumades.jsonform.shared.dispatch.validators;

import java.util.Map;

import com.gurumades.jsonform.shared.dispatch.JsonHelper;


@SuppressWarnings("rawtypes")
public class AllowedValuesValidator implements FormItemValidator  {
	
	@Override
	public void validate(Object item, Map<String, Object> values,
			ValidatorHelper helper) {
		JsonHelper jshelper  = ValidatorHelper.getJsonHelper();
		Map mapItem = jshelper.wrapItem(item);
		String allowedvalues = jshelper.getString(mapItem, "allowedValues", null);
		
		String fieldID = jshelper.getString(mapItem, "id", null);
		
		if (values == null && allowedvalues != null) {
			helper.addError(fieldID, "You should provide a value for this field.");
			return;
		}else if (allowedvalues == null){
			return;
		}

		Object val = values.get(fieldID);
		Map inner = jshelper.wrapItem(val);
		String value = (String) ((Map) inner.get("value")).get("value");
		
		if (allowedvalues != null) {
			String[] kV = allowedvalues.split(",");
			
			for (int i = 0; i < kV.length; i++) {
				String[] kV1 = kV[i].split("=");
					if (value.equals(kV1[0].trim())) {
						return;
					}
			}
		}
		
		if (jshelper.getBoolean(mapItem, "required", true) && value.equals("")) {
			helper.addError(fieldID, "This value is required");
		}else if (!value.equals("")) {
			helper.addError(fieldID, "This value is not allowed");
		}

	}
	
	@Override
	public boolean supportType(String type) {
		return type.startsWith("text-");
	}
}
